package com.h2cloud.gson;

/**
 * @Package: com.h2cloud.gson
 * @ClassName: CustomLabelPositionUsedAdapter
 * @Author: wulongkai
 * @CreateTime: 2023/7/21 17:03
 * @Description:
 */

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

public class CustomLabelPositionUsedAdapter extends TypeAdapter<LabelPositionUsed> {

    private final Gson gson = new Gson();

    @Override
    public void write(JsonWriter out, LabelPositionUsed value) throws IOException {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("label", value.getLabel());
        jsonObject.addProperty("value", value.getValue().toString()); // 将value字段的值转换为字符串
        jsonObject.addProperty("isChange", value.getIsChange());
        gson.toJson(jsonObject, out);
    }

    @Override
    public LabelPositionUsed read(JsonReader in) throws IOException {
        JsonObject jsonObject = gson.fromJson(in, JsonObject.class);
        String label = jsonObject.get("label").getAsString();
        String valueString = jsonObject.get("value").getAsString();
        Boolean isChange = jsonObject.get("isChange").getAsBoolean();

        LabelPositionUsed obj = new LabelPositionUsed();
        obj.setLabel(label);

        // 尝试将value字段的值转换为Integer类型
        try {
            obj.setValue(Integer.parseInt(valueString));
        } catch (NumberFormatException e) {
            // 如果转换失败，则保留原始字符串形式
            obj.setValue(valueString);
        }

        obj.setIsChange(isChange);
        return obj;
    }
}

